package com.wlbx.agent.net;

import android.util.Log;
import android.widget.Toast;


import com.luck.picture.lib.tools.ToastUtils;
import com.wlbx.agent.global.App;
import com.wlbx.agent.util.BaseUtils;
import com.wlbx.agent.util.RSAUtils;
import com.wlbx.agent.util.SPUtil;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;


public class TokenInterceptor implements Interceptor {

    private static final String TAG = TokenInterceptor.class.getSimpleName();

    /**
     * token异常错误代码:"errorCode":"6"
     */
    private static final String QUIT_STR = "\"code\":700";
    private static final String SERVER_EXCEPTION = "服务器异常";
    private static final String SERVER_RESTART = "Failed to connect";


    @Override
    public Response intercept(Chain chain) throws IOException {
        //这个chain里面包含了request和response，所以你要什么都可以从这里拿
        String time = String.valueOf(System.currentTimeMillis());
        String publicKey = ((String)SPUtil.get("Public-Key","")).replaceAll("[\\s*\t\n\r]", "");
        String enCodeTime = "";
        try {
            enCodeTime = RSAUtils.encrypt(time,RSAUtils.getPublicKey(publicKey)).replaceAll("[\\s*\t\n\r]", "");

        } catch (Exception e) {
            e.printStackTrace();
            Log.i(TAG,"ERRMES:"+e.getMessage());
        }
        Log.i(TAG,"time:"+time);
        Request.Builder requestBuilder=chain.request().newBuilder();
        if(!"".equals((String)SPUtil.get("Access-Token", "")))
            requestBuilder.addHeader("Access-Token", (String) SPUtil.get("Access-Token", ""));
        if(!"".equals(enCodeTime))
            requestBuilder.addHeader("Time-Stamp", enCodeTime);
        requestBuilder.removeHeader("User-Agent").addHeader("User-Agent", BaseUtils.getUserAgent(App.getContext()));
        Request request = requestBuilder.build();
        long t1 = System.nanoTime();//请求发起的时间
//        Log.e(TAG, String.format("发送请求 %s on %s%n%s",request.url(), chain.connection(), request.headers()));

        Response response = chain.proceed(request);

        long t2 = System.nanoTime();//收到响应的时间

        //这里不能直接使用response.body().string()的方式输出日志
        //因为response.body().string()之后，response中的流会被关闭，程序会报错，我们需要创建出一
        //个新的response给应用层处理
        ResponseBody responseBody = response.peekBody(1024 * 1024);

        String strResponse = responseBody.string();

//        Log.e(TAG, String.format("接收响应: %s %n返回json:%s %n%s",
//                response.request().url(),
//                strResponse,
//                response.headers()));
        //处理单点登录
        if (strResponse.contains(TokenInterceptor.QUIT_STR)) {
            App.sendQuitBroadcast();
        }

        return response;
    }


}
